//
//  NSString+URLOperator.m
//  SmartEstateCC
//
//  Created by 初唐科技 on 2018/1/26.
//  Copyright © 2018年 pretang. All rights reserved.
//

#import "NSString+URLOperator.h"

@implementation NSString (URLOperator)

- (BOOL)hasHTTPScheme
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    NSString *encodedURL = [self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
#pragma clang diagnostic pop
    NSURLComponents *URLComponents = [NSURLComponents componentsWithString:encodedURL];
    NSString *scheme = URLComponents.scheme.lowercaseString;
    return [scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"];
}

- (NSString *)URLValueForKey:(NSString *)key
{
    NSString *keyValue = [self URLKeyValueForKey:key];
    if (keyValue) {
        NSUInteger fromIndex = [keyValue rangeOfString:@"="].location + 1;
        return [keyValue substringFromIndex:fromIndex];
    }
    return nil;
}

- (NSString *)URLKeyValueForKey:(NSString *)key
{
    NSString *parttern = [NSString stringWithFormat:@"[^\?&]?%@=([^&]*)", key];
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:parttern options:0 error:&error];
    if (error) return nil;
    NSArray *results = [regex matchesInString:self options:0 range:NSMakeRange(0, self.length)];
    NSTextCheckingResult *result = results.firstObject;
    if (result) {
        NSString *keyValue = [self substringWithRange:result.range];
        return keyValue;
    }
    return nil;
}

- (NSString *)stringByUpdatingURLValue:(NSString *)value forKey:(NSString *)key
{
    NSString *oldKeyValue = [self URLKeyValueForKey:key];
    NSString *replaceURL = [self copy];
    if (oldKeyValue) {
        NSString *newKeyValue = [NSString stringWithFormat:@"%@=%@", key, value];
        replaceURL = [replaceURL stringByReplacingOccurrencesOfString:oldKeyValue withString:newKeyValue];
        return replaceURL;
    }
    return replaceURL;
}

- (NSString *)stringByAddingURLValue:(NSString *)value forKey:(NSString *)key
{
    NSString *oldKeyValue = [self URLKeyValueForKey:key];
    NSString *replaceURL = [self copy];
    NSString *newKeyValue = [NSString stringWithFormat:@"%@=%@", key, value];
    if (oldKeyValue) {
        replaceURL = [replaceURL stringByReplacingOccurrencesOfString:oldKeyValue withString:newKeyValue];
    }else {
        NSString *symbol = [replaceURL containsString:@"?"] ? @"&" : @"?";
        NSString *addingKeyValue = [NSString stringWithFormat:@"%@%@", symbol, newKeyValue];
        replaceURL = [replaceURL stringByAppendingString:addingKeyValue];
    }
    return replaceURL;
}

@end
